import { Body, Param, Controller, Get, Post, Patch, Query, Put } from '@nestjs/common';
import MemberService from '../service/MemberService';
import * as MemberReq from '../model/req/MemberReq';
import { ApiTags, ApiOperation, ApiParam, ApiQuery, ApiHeader } from '@nestjs/swagger';
import { Page, results, Err } from '../common/back';
import { query } from 'express';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
import { md5, randomSix } from '../common/index'
import { get } from 'http';

@ApiTags('用户')
@Controller("member")
export default class UserController {
  constructor(private readonly memberService: MemberService<any>) { }

  @ApiOperation({ summary: '登录', description: '登录' })
  @Post('loginMobile')
  async loginMobile(@Body() body: MemberReq.loginReq) {
    try {
      const Request = plainToClass(MemberReq.loginReq, body);
      const errors = await validate(Request);
      if (errors.length > 0) {
        return new Err(errors[0].constraints!.matches || errors[0].constraints!.isNotEmpty, 400);
      }

      body.password = md5(body.password);
      const existing = await this.memberService.login(body);
      if (typeof existing == "string") {
        return new Err(existing, 204);
      }
      Object.keys(existing).forEach((key) => {
        if (key === 'password' || key === 'user_type') {
          delete existing[key];
        }
      });
      return new results(existing);
      // let {
      //   user_id, user_name,nick_name, user_type,email, phonenumber,sex, avatar, login_ip,login_date, create_time,serial_num, spread_no,spread_id, level_id
      // } = existing;
      // return new results({
      //   user_id, user_name,nick_name, user_type,email, phonenumber,sex, avatar, login_ip,login_date, create_time,serial_num, spread_no,spread_id, level_id
      // });
    } catch (err: any) {
      return new Err(err.sqlMessage || '服务器错误', 500);
    }
  }

  @ApiOperation({ summary: '注册', description: '注册' })
  @Post('register')
  async userRegist(@Body() body: MemberReq.registerReq) {

    const Request = plainToClass(MemberReq.registerReq, body);
    const errors = await validate(Request);
    if (errors.length > 0) {
      return new Err(errors[0].constraints!.matches || errors[0].constraints!.isNotEmpty, 400);
    }

    try {
      const verCode = MemberReq.verCodeObj[body.phoneData];
      if (!verCode) {
        return new Err('验证码已过期，请重新获取', 400);
      }
      if (verCode != body.verCode) {
        return new Err('验证码错误', 400);
      }

      body.passData = md5(body.passData);
      const existing = await this.memberService.register(body);
      if (typeof existing == "string") {
        return new Err(existing, 204);
      }
      delete MemberReq.verCodeObj[body.phoneData];
      return new results("注册成功！请前往登录");
    } catch (err: any) {
      return new Err(err.sqlMessage || '服务器错误', 500);
    }
  }

  @ApiOperation({ summary: '获取手机验证码', description: '获取手机验证码' })
  @Get('getMobileCode/:mobileNo')
  async getMobileCode(@Param('mobileNo') mobileNo: string) {
    try {
      if (!mobileNo) {
        return new Err('未输入手机号', 400);
      }

      const verCode = randomSix(4);
      if (!MemberReq.verCodeObj[mobileNo]) {
        MemberReq.verCodeObj[mobileNo] = verCode;
        setTimeout(() => {
          delete MemberReq.verCodeObj[mobileNo];
        }, 300000); // 设置5分钟的过期删除
        return new results(verCode);
      }
      return new results(MemberReq.verCodeObj[mobileNo]);
    } catch (err: any) {
      return new Err(err.sqlMessage || '服务器错误', 500);
    }
  }


  @ApiOperation({ summary: '退出登录', description: "退出登录" })
  @Post('logout')
  async logout(@Body() body: MemberReq._idReq) {
    const Request = plainToClass(MemberReq._idReq, body);
    const errors = await validate(Request);
    if (errors.length > 0) {
      return new Err(errors[0].constraints!.matches || errors[0].constraints!.isNotEmpty, 400);
    }

    try {
      const existing = await this.memberService.logout(body);
      if (typeof existing == "string") {
        return new Err(existing, 401)
      }
      return new results("退出登录");
    } catch (err: any) {
      return new Err(err.sqlMessage || '服务器错误', 500);
    }
  }

  @ApiOperation({ summary: "获取用户基本信息", description: "获取用户基本信息" })
  @Get('getInfo')
  async getInfo(@Query() body: MemberReq._idReq) {
    const registerRequest = plainToClass(MemberReq._idReq, body);
    const errors = await validate(registerRequest);
    if (errors.length > 0) {
      return new Err(errors[0].constraints!.matches || errors[0].constraints!.isNotEmpty, 400);
    }

    try {
      const existing = await this.memberService.getUser(body.user_id);
      if (typeof existing == "string") {
        return new Err(existing, 401)
      }
      return new results(existing);
    } catch (err: any) {
      return new Err(err.sqlMessage || '服务器错误', 401);
    }
  }

  @ApiOperation({ summary: "修改密码", description: "修改密码" })
  @Post('updatePassword')
  async updatePassword(@Body() body: MemberReq.setPwd) {
    const registerRequest = plainToClass(MemberReq.setPwd, body);
    const errors = await validate(registerRequest);
    if (errors.length > 0) {
      return new Err(errors[0].constraints!.matches || errors[0].constraints!.isNotEmpty, 400);
    }

    try {
      body.newPwd = md5(body.newPwd);
      const data = await this.memberService.setPwd(body);
      if (typeof data == "string") {
        return new Err(data);
      }
      return new results("修改密码成功");
    } catch (err: any) {
      return new Err(err.sqlMessage || '服务器错误', 500)
    }
  }

}


// @ApiOperation({ summary: "获取用户附属信息", description: "获取用户附属信息" })
// @Get('getUserSubInfo')
// async getUserSubInfo(@Query() query: any) {
//   try {
//     return new results("用户附属信息");
//   } catch (err: any) {
//     return new Err(err.sqlMessage || '服务器错误', 401);
//   }
// }

// @ApiOperation({ summary: '推广汇总', description: '推广汇总' })
// @Get('mychildSumary')
// async mychildSumary(@Query() query: any) {
//   try {
//     return new results("推广汇总");
//   } catch (err: any) {
//     return new Err(err.sqlMessage || '服务器错误', 401);
//   }
// }

// @ApiOperation({ summary: '推广明细', description: '推广明细' })
// @Get('listChildrean')
// async listChildrean(@Query() query: any) {
//   try {
//     return new results("推广明细");
//   } catch (err: any) {
//     return new Err(err.sqlMessage || '服务器错误', 401);
//   }
// }